//
//  STMQiNiuManger.m
//  STTest
//
//  Created by imac on 2019/10/11.
//  Copyright © 2019 imac. All rights reserved.
//

#import "STTools_QnTokenCreateManger.h"
#import <Qiniu/QiniuSDK.h>
#import <UIKit/UIKit.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>

/*
 [qiniu]
 ACCESSKEY = AZjyJF3dSC-K00n1UKOLpa5D2RhR6iXGH5-jNDwW
 SECRETKEY = rZWhsaL9iOl5N1Al-WKYqx4Pmhsuiz0xfuvXpbSn
 bucket    = mengpa
 domain    = http://file.mengpaxing.com/
 */

#define STM_QN_AK @"AZjyJF3dSC-K00n1UKOLpa5D2RhR6iXGH5-jNDwW"
#define STM_QN_SK @"rZWhsaL9iOl5N1Al-WKYqx4Pmhsuiz0xfuvXpbSn"
@interface STTools_QnTokenCreateManger()

@end
@implementation STTools_QnTokenCreateManger
+ (STTools_QnTokenCreateManger *)manger{
    static STTools_QnTokenCreateManger * stoneobs_temp_manger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        stoneobs_temp_manger = STTools_QnTokenCreateManger.new;
    });
    return stoneobs_temp_manger;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self createtoken];
    }
    return self;
}
- (void)createtoken{
    NSString * stoneobs_temp_token = [self.class makeToken:STM_QN_AK secretKey:STM_QN_SK];
    self.token = stoneobs_temp_token;
}
+ (NSString*)dictionryToJSONString:(NSMutableDictionary *)dictionary
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


+ (NSString *) hmacSha1Key:(NSString*)key textData:(NSString*)text
{
    const char *cData  = [text cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
    uint8_t cHMAC[CC_SHA1_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:CC_SHA1_DIGEST_LENGTH];
    NSString *hash = [QNUrlSafeBase64 encodeData:HMAC];
    return hash;
}

+ (NSString *)makeToken:(NSString *)accessKey secretKey:(NSString *)secretKey
{
    //名字
    NSString *baseName = [self marshal];
    baseName = [baseName stringByReplacingOccurrencesOfString:@" " withString:@""];
    baseName = [baseName stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    NSData   *baseNameData = [baseName dataUsingEncoding:NSUTF8StringEncoding];
    NSString *baseNameBase64 = [QNUrlSafeBase64 encodeData:baseNameData];
    NSString *secretKeyBase64 =  [self hmacSha1Key:secretKey textData:baseNameBase64];
    NSString *token = [NSString stringWithFormat:@"%@:%@:%@",  accessKey, secretKeyBase64, baseNameBase64];
    
    return token;
}

+ (NSString *)marshal
{
    time_t deadline;
    time(&deadline);
    //"ceshi" 是我们七牛账号下创建的储存空间名字“可以自定义”
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"mengpa" forKey:@"scope"];
    //3464706673 是token有效期
    NSNumber *escapeNumber = [NSNumber numberWithLongLong:3464706673];
    [dic setObject:escapeNumber forKey:@"deadline"];
    NSString *json = [self dictionryToJSONString:dic];
    return json;
}

- (void)sendFileWithFilePath:(NSString *)path withKey:(NSString*)key handle:(void (^)(bool ))handle{
    NSString *token = self.token;
    QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
        builder.zone = [QNFixedZone zone2];
    }];
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *uploadOption = [[QNUploadOption alloc] initWithMime:@"" progressHandler:^(NSString *key, float percent) {
        // NSLog(@"percent == %.2f", percent);
    }
                                                                 params:nil
                                                               checkCrc:NO
                                                     cancellationSignal:nil];
    
    NSLog(@"文件filePath = %@",path);
    NSString * keyName = key;
    [upManager putFile:path key:keyName token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        // NSLog(@"info ===== %@", info);
        NSLog(@"上传图片结果 resp===== %@  info = %@  \n  key = %@", resp,info,key);
        if ([resp.allKeys containsObject:@"key"]) {
            NSString * imageUrl = [NSString stringWithFormat:@"%@%@",@"",resp[@"key"]];
            if (handle) {
                handle(YES);
            }
        }else{
            handle(NO);
        }
    }
                option:uploadOption];
}
@end
